<template>
    <div>
        <!-- 用户管理页面 -->
        <Card>
            <p slot="title" class="card-title">
                <Icon type="home"></Icon>
                <span>用户管理</span>
            </p>
            <div>
                <template>
                    <Row>
                        <Col span="15">
                            <Button type="info" @click="openAddModal(null)">
                                <Icon type="ios-medkit-outline"></Icon>&nbsp;添加用户
                            </Button>
                            <Button :disabled="setting.loading" type="success" @click="getData">
                                <Icon type="ios-refresh"></Icon>&nbsp;刷新数据
                            </Button>
                            <Button type="primary" @click="exportData(1)">
                                <Icon type="ios-download-outline"></Icon>&nbsp;导出表格
                            </Button>
                        </Col>
                        <Col span="9">
                            <Input v-model="search.value" placeholder="请输入您想要搜索的内容..." class="margin-bottom-10">
                            <Button slot="append" icon="ios-search"></Button>
                            </Input>
                        </Col>
                    </Row>
                    <Table ref="table" class="margin-bottom-10"
                           :columns="columns" :loading="setting.loading" :border="setting.showBorder"
                           :data="data.content"></Table>
                    <Page :total="data.totalElements" class="tr" @on-change="pageChange" :current.sync="data.number+1"
                          :page-size="data.size"
                          @on-page-size-change="pageSizeChange" show-elevator show-sizer></Page>
                </template>
            </div>
        </Card>

        <!-- 添加页面 -->
        <AddUser v-if="addUserModal" :roles="roles" @cancel="onModalCancel"/>

        <!-- 更新页面 -->
        <UpdateUser v-if="updateUserModal" :roles="roles" :uid="updateUserId" :update-object="updateObject"
                    @cancel="onModalCancel"/>

        <!-- 重置密码页面 -->
        <ResetPassword v-if="resetPasswordModal" :user="resetPasswordUser" @cancel="onModalCancel"/>

        <!-- 删除页面 -->
        <Modal v-model="removeModal" width="360">
            <p slot="header" style="color:#f60;text-align:center">
                <Icon type="information-circled"></Icon>
                <span>提示</span>
            </p>
            <div style="text-align:center">
                <p>此操作为不可逆操作，是否确认删除？</p>
                用户名:{{removeObject.username}}<br>
            </div>
            <div slot="footer">
                <Button type="error" size="large" long :loading="setting.loading" @click="removeUser(removeObject.uid)">确认删除</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
    import {post, get} from '@/libs/request'
    import AddUser from './components/add.vue'
    import UpdateUser from './components/update.vue'
    import ResetPassword from './components/reset-password.vue'

    export default {
        data() {
            return {
                // 传递的修改对象
                updateObject: {},
                // 传递修改用户id(弃用)
                updateUserId: null,
                // 开启添加用户页面
                addUserModal: false,
                // 开启修改用户页面
                updateUserModal: false,
                // 开启重置密码页面
                resetPasswordModal: false,
                // 开启删除页面
                removeModal: false,
                // 传递的更新密码
                resetPasswordUser: null,
                // 删除传递的对象
                removeObject: {
                    uid:'',
                    username:''
                },
                // 数据库中所有的角色
                roles: null,
                // selections:[],
                // 进度条
                setting: {
                    loading: true,
                    showBorder: true
                },
                // 搜索
                search: {
                    type: 'name',
                    value: ''
                },
                // 表格属性
                columns: [
                    {title: 'ID', key: 'uid', sortable: true},
                    {title: '用户名', key: 'username', sortable: true},
                    {title: '密码', key: 'password', sortable: true},
                    {
                        title: '状态',
                        key: 'status',
                        render: (h, params) => {
                            return h('span',
                                {
                                    style: {
                                        color: params.row.status == 1 ? 'green' : 'red'
                                    }
                                }, params.row.status == 1 ? '正常' : '锁定中')
                        },
                        sortable: true
                    },
                    {
                        title: '角色组',
                        key: 'roles',
                        render: (h, params) => {
                            let roles = []
                            if (params.row.roles != null && params.row.roles.length > 0) {
                                params.row.roles.forEach(element => {
                                    let role = h('Tag', {
                                        props: {
                                            color: "blue"
                                        }
                                    }, element.name);
                                    roles.push(role)
                                });
                                return h('div', roles)
                            }
                            return h('span', '空')
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 260,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {type: params.row.status == 1 ? 'success' : 'warning', size: 'small'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            this.lockUser(params.row)
                                        }
                                    }
                                }, (params.row.status == 1 || params.row.uid == 1) ? '锁定' : '恢复'),
                                h('Button', {
                                    props: {type: 'primary', size: 'small'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            this.openAddModal(params.row)
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {type: 'info', size: 'small'},
                                    style: {marginRight: '5px'},
                                    on: {
                                        click: () => {
                                            this.openAddModal(params.row, 'resetPassword')
                                        }
                                    }
                                }, '重置密码'),
                                h('Button', {
                                    props: {type: 'error', size: 'small'},
                                    on: {
                                        click: () => {
                                            this.removeModalOpen(params.row)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                // 表格数据
                data: {},
                // 分页
                dataFilter: {
                    page: 1,
                    pageSize: 10
                },

            }
        },
        components: {
            AddUser, UpdateUser, ResetPassword
        },
        created() {
            this.getData();
            this.getRoleList();
        },
        methods: {
            /**
             * @description 分页更换事件回调
             */
            pageChange(p) {
                this.dataFilter.page = p;
                this.getData();
            },
            /**
             * @description 分页每页显示数量改变事件回调
             */
            pageSizeChange(p) {
                this.dataFilter.pageSize = p;
                this.getData();
            },

            /**
             * @description 获取用户列表
             */
            async getData() {
                this.setting.loading = true;
                try {
                    let res = await post('/user/role/list', {
                        page: this.dataFilter.page - 1,
                        pagesize: this.dataFilter.pageSize
                    })
                    this.data = res.data;
                } catch (error) {
                    console.log(error)
                }
                this.setting.loading = false;
            },

            /**
             * @description 锁定/解锁用户
             */
            async lockUser(obj) {
                this.setting.loading = true;
                let status = obj.status;
                let req_rep = status == 1 ? 0 : 1;
                let req_msg = status == 1 ? '已锁定' : '已解锁';
                try {
                    let res = await get('/user/updateStatus',{"uid":obj.uid});
                    if(res.data.code != 705){
                        this.$Message.destroy();
                        this.$Message.success(req_msg);
                    }
                    obj.status = req_rep;
                } catch (error) {
                    console.log(error);
                }
                this.setting.loading = false;
            },

            /**
             * @description 获取角色列表
             */
            async getRoleList() {
                try {
                    let res = await post('/role/list', {
                        page: 0,
                        pageSize: 1000
                    })
                    this.roles = res.data.content;
                } catch (error) {
                    console.log(error)
                }
            },

            /**
             * @description 打开模态窗口
             * @param uid 用户ID
             * @param type 打开类型
             */
            openAddModal(obj, type = 'update') {
                let uid = null;
                if (obj != null) {
                    uid = obj.uid;
                }
                if (uid == null || type === 'update') {
                    if (this.roles == null) {
                        this.getRoleList();
                    }
                }
                if (uid == null) {
                    this.addUserModal = true;
                } else if (type === 'update') {
                    this.updateUserId = uid;
                    this.updateObject = obj;
                    this.updateUserModal = true;
                } else {
                    this.resetPasswordUser = obj;
                    this.resetPasswordModal = true;
                }
            },

            /**
             * @description 关闭模态窗口
             * @param type 窗口类型
             * @param reload 是否重新加载数据
             */
            onModalCancel(type, reload = false) {
                switch (type) {
                    case 'add': {
                        this.addUserModal = false;
                    }
                        ;
                        break;
                    case 'update': {
                        this.updateUserModal = false;
                    }
                        ;
                        break;
                    case 'resetPassword': {
                        this.resetPasswordModal = false;
                    }
                        ;
                        break;
                }
                if (reload) this.getData();
            },

            /**
             * 开启删除页面
             * @param id
             */
            removeModalOpen(removeObject) {
                this.removeModal = true;
                this.removeObject = removeObject;
                console.log(removeObject)
            },

            /**
             * @description 删除用户
             */
            async removeUser(uid) {
                this.removeModal = false;
                if (this.removeObject == null) {
                    this.$Message.warning("删除对象为空，无法继续执行！");
                    return false;
                }
                this.setting.loading = true;
                try {
                    let res = await get('/user/remove',{"uid":uid});
                    if(res.data.code != 705){
                        this.$Message.destroy();
                        this.$Message.success("删除成功");
                    }
                    this.getData();
                } catch (error) {
                    console.log(error)
                }
                this.setting.loading = false;
            },

            /**
             * @description 导出表格CSV
             */
            exportData(type) {
                if (type === 1) {
                    this.$refs.table.exportCsv({
                        filename: '用户数据-' + new Date().getTime(),
                        columns: this.columns.filter((col, index) => index > 1 && index < this.columns.length - 1),
                        data: this.data.content
                    });
                }
            }
        }
    }
</script>
